<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>车辆年检记录</title>
    <script src="/js/vue.js"></script>
    <script src="/js/axios.js"></script>
    <link rel="stylesheet" href="/element-ui/lib/theme-chalk/index.css">
    <script src="/element-ui/lib/index.js"></script>
    <style>
        .el-table th,.el-table .cell{
            text-align: center;
        }
        .el-dialog--center .el-dialog__body {
            padding-bottom: 0px;
        }
        .el-form-item {
            margin-bottom: 15px;
        }
        .el-radio__inner {border-radius: 2px;}
        .el-radio__input.is-checked .el-radio__inner::after {
            content: '';
            width: 8px;
            height: 3px;
            border: 2px solid white;
            border-top: transparent;
            border-right: transparent;
            text-align: center;
            display: block;
            position: absolute;
            top: 2px;
            left: 1px;
            vertical-align: middle;
            transform: rotate(-45deg);
            border-radius: 0px;
            background: none;
        }
        .el-upload-dragger .el-icon-upload {
            font-size: 30px;
            color: #C0C4CC;
            margin: 5px 0 0px;
            line-height: 30px;
        }
        /*下面这几行代码就是设置上传框的长宽，可以按百分比来设置也可以用px去设置*/
          .el-upload .el-upload-dragger {
              width: 250px;
              height:85px;
          }
    </style>
</head>
<body>
<div id="app">

    <el-card shadow="always">
        <div slot="header">
            <span>车服租赁管理</span>
        </div>
        <!-- 面包屑 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>基础信息管理</el-breadcrumb-item>
            <el-breadcrumb-item>车辆年检记录</el-breadcrumb-item>
        </el-breadcrumb>
    </el-card>

    <el-card shadow="always">
        <el-form :inline="true" :model="param" class="demo-form-inline">
            <el-form-item label="日期">
                <el-date-picker
                        v-model="param.maintenanceDate"
                        value-format="yyyy-MM-dd"
                        type="date"
                        placeholder="请选择查询日期" clearable>
                </el-date-picker>
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="param.maintenanceState" placeholder="请选择状态" style="width: 120px">
                    <!-- 省略label，默认与value一样 -->
                    <el-option
                            v-for="item in types"
                            :key="item.maintenanceState"
                            :label="item.name"
                            :value="item.maintenanceState">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit" icon="el-icon-search" size="medium">查询</el-button>
                <el-button type="primary" @click="resetCondition" icon="el-icon-search" size="medium">重置</el-button>
                <el-button type="success" @click="showDialog" icon="el-icon-circle-plus" size="medium">添加</el-button>
                <el-button type="danger" size="medium" icon="el-icon-delete-solid" @click="deleteBatch">删除</el-button>
                <!--
              action: 上传地址
              name: 表单项名字，与控制器中MultipartFile类型的形参名字要一样
              show-file-list：隐藏上传的文件列表
              accept：限制选择的文件类型为Excel的类型
              display: inline 样式显示在同一行
              Excel格式：xls或xlsx
              -->
                <el-upload
                        style="display: inline; margin-left: 10px;"
                        action="/carAnnualExamination/import"
                        name="file"
                        :show-file-list="false"
                        accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                        :on-success="handleSuccess">
                    <el-button size="medium" type="primary" icon="el-icon-upload">导入Excel</el-button>
                </el-upload>
                <el-button type="warning" icon="el-icon-printer" size="medium" @click="exportExcel">导出Excel</el-button>
            </el-form-item>
        </el-form>

        <el-table
                :default-sort = "{prop: 'maintenanceDate', order: 'descending'}"
                ref="multipleTable"
                :data="pageBean.list"
                tooltip-effect="dark"
                style="width: 100%"
                @selection-change="handleSelectionChange">
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>

            <el-table-column
                    prop="carNumber"
                    label="车牌号"
                    width="120">
            </el-table-column>

            <el-table-column
                    prop="frameNumber"
                    label="车架号"
            width="120">
            </el-table-column>

            <el-table-column
                    sortable
                    prop="maintenanceDate"
                    label="年检日期"
            width="110">
            </el-table-column>

            <el-table-column
                    prop="operatingMileage"
                    label="运营里程数"
            width="110">
                <template slot-scope="scope">
                    {{ scope.row.operatingMileage }}公里
                </template>
            </el-table-column>

            <el-table-column
                    prop="yearlyInspectionIdentification"
                    label="年检标识"
                    width="120">
                <template slot-scope="scope">
                    <img :src="scope.row.yearlyInspectionIdentification" alt="年检标识" width="100" height="80">
                </template>
<!--                <el-image style="width: 120px; height: 80px;" :src="url" fit="contain"></el-image>-->
            </el-table-column>

            <el-table-column
                    prop="maintenanceState"
                    label="年检状态"
                    width="110">
                <template slot-scope="scope">
                    <el-tag v-if=" scope.row.maintenanceState===0" type="danger">未年检</el-tag>
                    <el-tag v-if=" scope.row.maintenanceState===1" type="success">已年检</el-tag>
                    <el-tag v-if=" scope.row.maintenanceState===2" >年检中</el-tag>
                </template>
            </el-table-column>

            <el-table-column label="操作" width="240">
                <template slot-scope="scope">
                    <el-button-group>
                        <el-button
                                size="small" icon="el-icon-view"
                                type="success"
                                @click="viewForm(scope.row)">查看
                        </el-button>
                        <el-button
                                size="small" icon="el-icon-edit"
                                type="primary"
                                @click="handleEdit(scope.$index, scope.row)">编辑
                        </el-button>
                        <el-button
                                size="small"
                                type="danger" icon="el-icon-delete"
                                @click="handleDelete(scope.$index, scope.row)">删除
                        </el-button>
                    </el-button-group>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination style="margin-top: 10px"
                       background
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page="param.pageNum"
                       :page-sizes="[5, 10, 15]"
                       :page-size="param.pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="pageBean.total">
        </el-pagination>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog
            title="车辆年检添加/修改"
            :visible.sync="dialogVisible"
            width="550px"
            top center
            :before-close="resetForm">

        <!-- 表单 -->
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm" :disabled="disabled">
            <el-form-item label="车牌号：" prop="carNumber" label-width="150px">
                <el-select
                        v-model="ruleForm.carId" style="width:250px"
                        filterable
                        clearable
                        remote
                        reserve-keyword
                        placeholder="车牌号"
                        :remote-method="remoteMethodCarNumber"
                        :loading="loading">
                    <el-option
                            v-for="item in insuranceList"
                            :key="item.id"
                            :label="item.carNumber"
                            :value="item.carId"
                            >
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="车架号：" prop="frameNumber" label-width="150px">
                <el-select
                        v-model="ruleForm.carId" style="width:250px"
                        filterable
                        clearable
                        remote
                        reserve-keyword
                        placeholder="车架号"
                        :remote-method="remoteMethodCarNumber"
                        :loading="loading">
                    <el-option
                            v-for="item in insuranceList"
                            :key="item.id"
                            :label="item.frameNumber"
                            :value="item.carId"
                            >
                    </el-option>
                </el-select>
            </el-form-item>

            <!-- 这里要设置value-format格式，不然提交到服务器无法转成JSON -->
            <el-form-item label="年检日期：" prop="maintenanceDate" label-width="150px">
                <el-date-picker style="width: 250px;"
                                v-model="ruleForm.maintenanceDate"
                                value-format="yyyy-MM-dd"
                                type="date"
                                placeholder="年-月-日">
                </el-date-picker>
            </el-form-item>

            <el-form-item label="上传年检标识：" prop="yearlyInspectionIdentificationName" label-width="150px">
                <el-upload
                        ref="upload"
                        :show-file-list="true"
                        :file-list="fileList"
                        v-model="ruleForm.yearlyInspectionIdentificationName"
                        drag
                        action="/file/upload"
                        name="file"
                        :on-success="uploadSuccess">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <!-- <div class="el-upload__tip" slot="tip">文件大小不超过1000kb</div>-->
                </el-upload>
<!--                   <el-image style="width: 150px; height: 80px;" :src="url" fit="contain"></el-image>-->
            </el-form-item>
            <el-form-item label="运营里程数：" prop="operatingMileage" label-width="150px">
                <el-input v-model="ruleForm.operatingMileage" placeholder="请输入运营里程数" style="width:250px"></el-input>
            </el-form-item>

            <el-form-item label="当前年检状态：" prop="maintenanceState" label-width="150px">
                <el-radio-group v-model="ruleForm.maintenanceState">
                    <el-radio :label="0">未年检</el-radio>
                    <el-radio :label="1">已年检</el-radio>
                    <el-radio :label="2">年检中</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="年检提醒：" prop="yearlyInspectionReminder" label-width="150px">
                <el-switch
                        v-model="ruleForm.yearlyInspectionReminder"
                        :active="switchValue"
                        active-text="ON"
                        inactive-text="OFF"
                        :active-value=1
                        :inactive-value=0
                        active-color="#13CE66"
                        inactive-color="#E6A23C">
                </el-switch>
            </el-form-item>

            <el-form-item label="备注：" prop="remark" label-position="left" label-width="150px">
                <el-input type="textarea" v-model="ruleForm.remark" placeholder="请输入内容" style="width:250px">
                </el-input>
            </el-form-item>

        </el-form>

        <span slot="footer" class="dialog-footer">
                <el-button type="primary" v-if="showButton" @click="submitForm('ruleForm')">确定</el-button>
                <el-button @click="resetForm('ruleForm')">取消</el-button>
        </span>

    </el-dialog>

</div>
<script type="text/javascript">
    new Vue({
        el: "#app",
        data() {
            return {
                switchValue: false, // 设置默认值为 true
                url:"",//显示地址
                filename:"",//
                //一页数据对象
                pageBean: {},
                //提交参数对象
                param: {
                    maintenanceDate: null,
                    maintenanceState: null,
                    pageNum: 1,
                    pageSize: 5
                },
                //添加模式
                addModel: true,
                multipleSelection: [],
                dialogVisible: false,
                //查看按钮显示
                disabled:false,
                //确定按钮显示
                showButton:true,
                ruleForm: {},  //表单数据
                loading: false,  //是否远程加载
                options: [],  //车架号下拉选项列表
                insuranceList:[],//保险列表
                carNumberOptions: [],  //车牌号下拉选项列表
                fileList: [],//上传文件列表
                types: [
                    {
                        maintenanceState: 0,
                        name: '未年检'
                    }, {
                        maintenanceState: 1,
                        name: '已年检'
                    },
                    {
                        maintenanceState: 2,
                        name: '年检中'
                    }
                ],
                rules: {
                    // carNumber: [
                    //     {required: true, message: '车牌号不能为空', trigger: 'change'},
                    //     // {validator: validateNumberExists, trigger: 'blur'},
                    // ],
                    // frameNumber: [
                    //     {required: true, message: '车架号不能为空', trigger: 'change'}
                    // ],
                    maintenanceDate: [
                        {required: true, message: '请选择年检日期', trigger: 'change'}
                    ],
                    // yearlyInspectionIdentificationName: [
                    //     {required: true, message: '请上传年检标识', trigger: 'blur'}
                    // ],
                    operatingMileage: [
                        {required: true, message: '运营里程数不能为空', trigger: 'blur'}
                    ],
                    maintenanceState: [
                        {required: true, message: '当前年检状态', trigger: 'change'}
                    ]

                }  //验证规则
            }
        },
        methods: {
            //上传成功的回调函数: 响应对象，文件对象，文件列表
            uploadSuccess(response,file,fileList){
                console.log(response,file,fileList);
                if (response){
                    //success
                    //this.$message.success("文件上传成功");
                    //显示图片
                    this.url = "/file/" + response;
                    this.ruleForm.yearlyInspectionIdentificationName = response;
                    this.ruleForm.yearlyInspectionIdentification = "/file/" + response;
                    console.log(this.url)
                    //this.fileList = []; // 清空文件列表
                }
                else {
                    this.$message.error("文件上传失败");
                }
            },
            //查看
            viewForm(row){
                this.disabled=true;
                this.showButton=false;
                //清空表单写入不了问题
                this.dialogVisible = true;
                //复制数据
                let data = Object.assign({}, row);
                //将数据赋值给ruleForm
                this.ruleForm = data;
            },
            //重置按钮搜索
            resetCondition(){
                this.param = {
                    maintenanceDate: null,
                    maintenanceState: null,
                    pageNum: 1,
                    pageSize: 5
                };
                this.findByPage();
            },
            //导出Exel
            exportExcel() {
                location.href = "/carAnnualExamination/export";
            },
            //上传成功
            handleSuccess(resp) {
                this.$message.success(resp);
                //重新加载数据
                this.findByPage();
            },
            //显示对话框
            showDialog() {
                //清空表单写入不了问题
                this.dialogVisible = true;
                this.showButton = true;
                //dom创建完成才能执行
                this.$nextTick(() => {
                    //清空表单和验证规则
                    this.$refs.ruleForm.clearValidate();
                    this.$refs.ruleForm.resetFields();
                    this.ruleForm = {};
                });
                //添加模式
                this.addModel = true;
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            //编辑按钮
            handleEdit(index, row) {
                //编辑模式
                this.addModel = false;
                this.disabled = false;
                this.showButton=true;
                //复制数据
                let data = Object.assign({}, row);
                //将数据赋值给ruleForm
                this.ruleForm = data;
                //打开对话框
                this.dialogVisible = true;
                //dom创建完成才能执行
                this.$nextTick(() => {
                    //清空验证规则
                    this.$refs.ruleForm.clearValidate();
                });
                //this.fileList = []; // 清空文件列表
            },
            //删除
            handleDelete(index, row) {
                this.$confirm(`此操作将永久删除车辆年检记录：${row.carNumber}, 是否继续?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //调用服务器端来删除
                    axios.get(`/carAnnualExamination/deleteById?id=${row.id}`).then(resp => {
                        let result = resp.data;
                        if (result.code) {
                            this.$message.success(result.message);
                        } else {
                            this.$message.error("删除车辆年检记录失败");
                        }
                        //重新加载
                        this.findByPage();
                    });
                }).catch(() => {
                    //什么也不写
                });
            },
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.param.pageSize = val;
                this.findByPage();
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.param.pageNum = val;
                this.findByPage();
            },
            //查询按钮
            onSubmit() {
                this.findByPage();
            },
            //分页查询
            findByPage() {
                axios.post("/carAnnualExamination/findPage", this.param).then(resp => {
                    //resp.data得到Result对象，再获取其中data属性
                    this.pageBean = resp.data.data;
                });
            },
            //添加
            add() {
                axios.post("/carAnnualExamination/save", this.ruleForm).then(resp => {
                    let result = resp.data;
                    //carId绑定赋值
                    this.ruleForm.carId = result.carId;
                    if (result.code) {
                        this.$message.success(result.message);
                    }
                }).catch(err => {
                    this.$message.error("添加车辆年检记录失败，错误信息是：" + err.message);
                }).finally(() => {
                    this.ruleForm = {};
                    //清除验证错误信息
                    this.$refs.ruleForm.clearValidate();
                    this.fileList = []; // 清空文件列表
                    this.dialogVisible = false;
                    //查询记录
                    this.findByPage();
                });
            },
            //修改
            update() {
                axios.post("/carAnnualExamination/update", this.ruleForm).then(resp => {
                    let result = resp.data;
                    if (result.code) {
                        this.$message.success(result.message);
                    }
                }).catch(err => {
                    this.$message.error("修改年检记录失败，错误信息是：" + err.message);
                }).finally(() => {
                    this.ruleForm = {};
                    //清除验证错误信息
                    this.$refs.ruleForm.clearValidate();
                    this.dialogVisible = false;
                    //查询车位
                    this.findByPage();
                });
            },
            //批量删除
            deleteBatch() {
                //判断是否选中
                if (this.multipleSelection.length == 0) {
                    this.$message.warning("请先选中要删除的数据");
                    return;
                }
                //删除前确认
                this.$confirm(`此操作将永久删除${this.multipleSelection.length}条年检记录,是否继续?`, '提示',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                    //1.把对象数组转成id的数组 (row表示数组中每个元素)
                    let ids = this.multipleSelection.map(row => row.id);
                    console.log(ids);
                    //2.发送删除操作给服务器端
                    axios.post("/carAnnualExamination/deleteBatch", ids).then(resp => {
                        //获取删除的行数
                        let num = resp.data.data;
                        this.$message.success(`成功删除${num}条年检记录`);
                        //重新加载表格数据
                        this.findByPage();
                    });
                }).catch(() => {
                    //不做什么
                });
            },
            //确定按钮
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        if (this.addModel) {
                            //添加方法
                            this.add();
                            //提交文件
                            this.$refs.upload.submit();
                        } else {
                            this.update();
                            //提交文件
                            this.$refs.upload.submit();
                        }
                    } else {
                        return false;
                    }
                });
            },
            resetForm(formName) {
                // this.$refs[formName].resetFields();
                this.$refs.ruleForm.resetFields();
                this.ruleForm = {};
                this.dialogVisible = false;
                this.disabled = false;//打开禁用表单
                this.fileList = []; // 清空文件列表
            },
            //远程加载的方法, query输入的字符串 (车架名字)
            remoteMethod(query) {
                if (query !== '') {
                    //开始远程加载 (有个可以转动的图标)
                    this.loading = true;
                    //后台通过车架号模糊查询
                    axios.get(`/car/findByFrameNumber?frameNumber=${query}`).then(resp => {
                        this.loading = false;  //不转了
                        this.options = resp.data.data;
                    });
                } else {
                    this.options = [];
                }
            },
            //车牌号远程查找
            remoteMethodCarNumber(query) {
                if (query !== '') {
                    //开始远程加载 (有个可以转动的图标)
                    this.loading = true;
                    //后台通过车牌号模糊查询
                    axios.get(`/car/findByCarNumber?carNumber=${query}`).then(resp => {
                        this.loading = false;  //不转了
                        this.carNumberOptions = resp.data.data;
                    });
                } else {
                    this.carNumberOptions = [];
                }
            },
            //绑定car同一个id
            findInsureList(){
                axios.get("/carInsure/findInsureList").then(resp => {
                    this.insuranceList = resp.data.data;
                })
            }
        },
        created() {
            this.findByPage();
            this.findInsureList();
        }
    });
</script>
</body>
</html>